package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.annotations.Auth;
import cn.thoughtworks.school.entities.Stack;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.handlers.BusinessException;
import cn.thoughtworks.school.services.StackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api/v3/stacks")
public class StackController {
  @Autowired
  private StackService stackService;

  @Autowired
  private RestTemplate template;

  @RequestMapping(value = "", method = RequestMethod.GET)
  public ResponseEntity findAll(@Auth User current) {
    List<Stack> stacks = stackService.findStacksByOrganization(current);
    return ResponseEntity.ok(stacks);
  }

  @RequestMapping(value = "/pageable", method = RequestMethod.GET)
  public ResponseEntity findAllTags(@RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer size,
                                    @Auth User current) {

    Sort sort = new Sort(Sort.Direction.DESC, "createTime");
    Pageable pageable = new PageRequest(page - 1, size, sort);
    Page<Stack> stacks = stackService.findStackPageableByOrganization(current, pageable);

    return new ResponseEntity<>(stacks, HttpStatus.OK);
  }

  @RequestMapping(value = "", method = RequestMethod.POST)
  public ResponseEntity addStack(@RequestBody Map data,
                                 @Auth User current) throws BusinessException {
    String image = (String) data.get("image");
    if (isExistImage(image)) {
      throw new BusinessException("未找到当前镜像的该版本");
    }
    Stack stack = stackService.findStackByImageAndOrganization(image,current);
    if (Objects.nonNull(stack)) {
      throw new BusinessException("该镜像已存在");
    }
    stack = stackService.addStack(data, current);
    return new ResponseEntity<>(stack, HttpStatus.CREATED);
  }

  private boolean isExistImage(String image) {
    String[] images = image.split(":");
    String url = "https://registry.hub.docker.com/v1/repositories/" + images[0] + "/tags";

    List<Map> tags= template.getForEntity(url, List.class).getBody();

    Map imageTag = tags.stream().filter(tag -> tag.get("name").equals(images[1])).findFirst().orElse(null);
    return Objects.isNull(imageTag);
  }

}
